package com.ktjy.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ktjy.dto.UserDTO;
import com.ktjy.pojo.SysUser;
import com.ktjy.service.ISysUserService;
import com.ktjy.utils.AjaxResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.log4j.Log4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author jjx
 * @since 2025-07-28
 */

@RestController
@RequestMapping("/api/sys/user")
@Tag(name="用户模块")
public class SysUserController {
    Logger log= LoggerFactory.getLogger(SysUserController.class);

    @Resource
    ISysUserService sysUserService;

    @GetMapping("/list")
    @PreAuthorize("@ss.hasPerm('system:user:list')")
    @Operation(summary="用户列表接口")
    public AjaxResult list(UserDTO userDTO,
                           @Parameter(description = "页码数") @RequestParam(value = "pageNo",defaultValue = "1") Integer pageNo,
                           @Parameter(description = "每页显示条数")@RequestParam(value = "pageSize",defaultValue = "5") Integer pageSize){
        IPage<SysUser> page = sysUserService.findPage(userDTO, pageNo, pageSize);
        return AjaxResult.success(page);
    }

    @PostMapping("/save")
    @PreAuthorize("@ss.hasPerm('system:user:add')")
    public AjaxResult saveOrUpdate(@RequestBody SysUser sysUser){
        try {
            sysUserService.saveOrUpdateUser(sysUser);
            return AjaxResult.success("保存成功");
        } catch (Exception e) {
            log.error("SysUserController中saveOrUpdate方法执行报错的。",e);
        }
        return AjaxResult.error("保存失败");
    }

    @PutMapping("/resetPwd")
    @PreAuthorize("@ss.hasPerm('system:user:resetPwd')")
    public AjaxResult resetPwd(@RequestBody SysUser user){
        try {
            boolean ok=sysUserService.updateById(user);
            if(ok){
                return AjaxResult.success("重置密码成功");
            }
        } catch (Exception e) {
            log.error("SysUserController中resetPwd方法执行报错的。",e);
        }
        return AjaxResult.error("重置密码失败");
    }

    @GetMapping("/view/{id}")
    @PreAuthorize("@ss.hasPerm('system:user:query')")
    public AjaxResult view(@PathVariable("id") Long id){
        //查询用户详情
        try {
            SysUser sysUser=sysUserService.findUser(id);
            if(sysUser!=null){
                return AjaxResult.success(sysUser);
            }
        } catch (Exception e) {
            log.error("SysUserController中view方法执行报错的。",e);
        }
        return AjaxResult.error();
    }

    @DeleteMapping("/del/{id}")
    @PreAuthorize("@ss.hasPerm('system:user:remove')")
    public AjaxResult del(@PathVariable("id") Long id){
        try {
            sysUserService.deleteUser(id);
            return AjaxResult.success("删除成功");
        } catch (Exception e) {
            log.error("SysUserController中del方法执行报错的。",e);
        }
        return AjaxResult.error("删除失败");
    }

    @GetMapping("/checkNameUnique")
    public AjaxResult checkNameUnique(@RequestParam("name") String name){
        try {
            boolean ok = sysUserService.checkNameUnique(name);
            if(!ok){//数据库不存在该账号
                return AjaxResult.success();
            }
        } catch (Exception e) {
            log.error("SysUserController中checkNameUnique方法执行报错的。",e);
        }
        return AjaxResult.error();
    }

//    @GetMapping("/export")
//    public void exportExcel(UserDTO userDTO, HttpServletResponse response){
//        //1. 查询需要导出的数据
//        List<SysUser> list = sysUserService.findList(userDTO);
//        //2. 得到一个excel文件
//        Workbook workbook=sysUserService.exportExcel("用户数据",list);
//        //输出流输出给浏览器
//        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//        response.setCharacterEncoding("utf-8");
//        ServletOutputStream out=null;
//        try {
//            //设置下载文件的名称
//            response.setHeader("Content-Disposition","attachment; filename="+ URLEncoder.encode("用户信息","UTF-8")+".xlsx");
//            out = response.getOutputStream();
//            workbook.write(out);
//        } catch (Exception e) {
//                    log.info("SysUserController中exportExcel方法执行报错的。",e);
//        } finally {
//            if(out!=null){
//                try {
//                    out.close();
//                } catch (IOException e) {
//                    out=null;
//                }
//            }
//        }
//    }
@GetMapping("/export")
public void exportExcel(UserDTO userDTO, HttpServletResponse response){
    //1. 查询需要导出的数据
    List<SysUser> list = sysUserService.findList(userDTO);
    //2. 得到一个excel文件
//        Workbook workbook=sysUserService.exportExcel("用户数据",list);
    ExportParams exportParams=new ExportParams();
//        exportParams.setTitle("字节滚动有限公司");
    exportParams.setSheetName("用户数据");
    Workbook workbook= ExcelExportUtil.exportExcel(exportParams,SysUser.class,list);

    //输出流输出给浏览器
    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    response.setCharacterEncoding("utf-8");
    ServletOutputStream out=null;
    try {
        //设置下载文件的名称
        response.setHeader("Content-Disposition","attachment; filename="+ URLEncoder.encode("用户信息","UTF-8")+".xlsx");
        out = response.getOutputStream();
        workbook.write(out);
    } catch (Exception e) {
        log.error("SysUserController中exportExcel方法执行报错的。",e);
    } finally {
        if(out!=null){
            try {
                out.close();
            } catch (IOException e) {
                out=null;
            }
        }
    }
}
    @PostMapping("/import")
    public AjaxResult importExcel(MultipartFile file){
        //1.解析excel中的数据得到用户对象
        List<SysUser> list=sysUserService.importExcel(file);
        //2.将用户对象存储到数据库
        boolean ok = sysUserService.saveBatch(list);
        if(ok){
            return AjaxResult.success("导入成功");
        }
        return AjaxResult.error("导入失败");
    }
}
